package com.learn.excel.core.util;

import com.google.common.collect.Lists;
import org.apache.commons.lang3.StringUtils;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;
import java.net.InetAddress;
import java.net.UnknownHostException;
import java.util.List;

public class IpUtils {
    public static String getIpAddr(HttpServletRequest request) {
        String ipAddress = null;
        try {
            ipAddress = request.getRemoteAddr();
            // 从header中获取
            if (isNull(ipAddress)) {
                ipAddress = getIpByHeader(request);
            }
            if ("127.0.0.1".equals(ipAddress)) {
                // 根据网卡取本机配置的IP
                InetAddress inet = null;
                try {
                    inet = InetAddress.getLocalHost();
                } catch (UnknownHostException e) {
                    e.printStackTrace();
                }
                ipAddress = inet.getHostAddress();
            }
            // 对于通过多个代理的情况，第一个IP为客户端真实IP,多个IP按照','分割
            if (ipAddress != null && ipAddress.length() > 15) {
                if (ipAddress.indexOf(",") > 0) {
                    ipAddress = ipAddress.substring(0, ipAddress.indexOf(","));
                }
            }
        } catch (Exception e) {
            ipAddress = "";
        }
        return "0:0:0:0:0:0:0:1".equals(ipAddress) ? "127.0.0.1" : ipAddress;
    }

    public static String getIpAddr() {
        ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
        HttpServletRequest req = attributes.getRequest();
        return getIpAddr(req);
    }

    /***
     * 从header中获取IP
     * @param request
     * @return
     */
    private static String getIpByHeader(HttpServletRequest request) {
        String ipAddress = null;
        List<String> headers = Lists.newArrayList("x-real-ip", "x-forwarded-for", "Proxy-Client-IP", "WL-Proxy-Client-IP");
        for (String header : headers) {
            ipAddress = request.getHeader(header);
            if (!isNull(ipAddress)) {
                break;
            }
        }
        return ipAddress;
    }

    /***
     * 判断ip是否为空
     * @param ipAddress
     * @return
     */
    private static boolean isNull(String ipAddress) {
        if (StringUtils.isBlank(ipAddress) || "unknown".equalsIgnoreCase(ipAddress)) {
            return true;
        }
        return false;
    }
}
